package com.samehope.ar.service.impl;

import com.samehope.ar.entity.DeviceRecord;
import com.samehope.ar.entity.SysRole;
import com.samehope.ar.entity.SysUser;
import com.samehope.ar.mapper.SysUserMapper;
import com.samehope.ar.service.IDeviceRecordService;
import com.samehope.ar.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.samehope.ar.util.JwtTokenUtil;
import com.samehope.ar.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author ZhangLuo
 * @since 2019-12-31
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private IDeviceRecordService deviceRecordService;
    /**
     * 根据手机号码查找用户
     * @param mobile
     * @return
     */
    @Override
    public SysUser getByMobile(String mobile) {
        return this.baseMapper.findByMobile(mobile);
    }

    /**
     * 根据用户查找用户角色
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> getRoleListByUser(Long userId) {
        return this.baseMapper.getRoleListByUserAndCompanyAndProject(userId,
                SessionUtil.getCompanyId(), SessionUtil.getProjectId());
    }

    /**
     * 用户登录
     * @param mobile
     * @param password
     * @return
     */
    @Override
    public String login(String mobile, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            SysUser sysUser = this.baseMapper.findByMobile(mobile);
            if (sysUser == null) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }

            if(!passwordEncoder.matches(password, sysUser.getPwd())){
                throw new BadCredentialsException("密码不正确");
            }

            token = jwtTokenUtil.generateToken(sysUser);

            DeviceRecord record = new DeviceRecord();
            record.setDeviceId(SessionUtil.getDeviceId());
            record.setCompanyId(sysUser.getCompanyId());
            record.setUserId(sysUser.getId());
            record.setRecord(MessageFormat.format("用户: {0}, 使用设备登录", sysUser.getMobile()));
            record.setCreateBy(sysUser.getId());
            record.setCreateDate(LocalDateTime.now());
            deviceRecordService.save(record);
        } catch (AuthenticationException e) {
            log.error("登录异常:{}", e.getMessage());
        }
        return token;
    }
}
